#include "app_pool.h"
#include <mqueue.h>
#include <pthread.h>
#include "log/log.h"
#include <stdlib.h>

static char *mq_name = "/app_pool_mq";
static mqd_t mqd;
static pthread_t *threads;  //线程池
static int thread_num;  //线程池中线程的数量

void *app_pool_thread(void *arg)
{
    Task task;
    //从消息队列中获取任务
    while (1) {
        ssize_t size = mq_receive(mqd, (char *)&task, sizeof(Task), NULL);
        if (size == sizeof(Task)) 
        {
            task.tast_func(task.arg);
        }
    }

}

int app_pool_init(int size)
{
    //队列属性
    struct mq_attr attr;
    attr.mq_maxmsg = 10; //队列中最大消息数
    attr.mq_msgsize = sizeof(Task); //每个消息的最大字节数
    //创建消息队列
    mqd = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    if (mqd == -1) {
        log_debug("mq_open failed");
    }
    else
    {
        log_debug("mq_open success");
    }

    //创建线程池
    thread_num = size;
    threads = (pthread_t *)malloc(sizeof(pthread_t) * size);
    for (int i = 0; i < size; i++) {
        pthread_create(&threads[i], NULL, app_pool_thread, NULL);
    }

    return 0;
}

void app_pool_close(void)
{
    //关闭消息队列
    mq_close(mqd);
    mq_unlink(mq_name);
    //关闭线程池
    for (int i = 0; i < thread_num; i++) {
        pthread_cancel(threads[i]);     //终止线程
        pthread_join(threads[i], NULL);  //等待线程结束
    }

    //释放线程池    
    free(threads);
}

int app_pool_registerTask(int (*task_func)(void *), void *arg)
{
    //创建任务
    Task *task = (Task *)malloc(sizeof(Task));
    task->tast_func = task_func;
    task->arg = arg;
    
    //将任务加入消息队列
    mq_send(mqd, (char *)task, sizeof(Task), 1);
    //释放任务
    free(task);
    return 0;
}
